import { nanoid } from 'nanoid'
import React, { Fragment, useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'
// import { nanoid } from 'nanoid'

import { addPerson } from '../../redux/slices/persons'

const Person = () => {
	const dispatch = useDispatch()

	const nameNode = useRef()
	const ageNode = useRef()

	const persons = useSelector(state => state.persons.value)
	const count = useSelector(state=>state.count.value)


	const add = () => {
		const name = nameNode.current.value
		const age = ageNode.current.value
		const newPerson = { id: nanoid(), name, age }
		dispatch(addPerson(newPerson))
		nameNode.current.value = ''
		ageNode.current.value = ''
	}
	return (
		<Fragment>
			<h1>当前为Person组件，Count组件求和为{count}</h1>
			<input ref={nameNode} type="text" placeholder="输入名字" />
			&nbsp;
			<input ref={ageNode} type="text" placeholder="输入年龄" />
			&nbsp;
			<button onClick={add}>添加</button>
			<ul>
				{persons.map(p => {
					return (
						<li key={p.id}>
							{p.name}--{p.age}
						</li>
					)
				})}
			</ul>
		</Fragment>
	)
}
export default Person

/* class Person extends Component {
	addPerson = () => {
		const name = this.nameNode.value
		const age = this.ageNode.value
        const newPerson = {id:nanoid(),name,age}
        this.props.addPerson(newPerson)
        this.nameNode.value=''
        this.ageNode.value=''
	}

	render() {
		return (
			<div>
				<h1>当前为Person组件，Count组件求和为{this.props.count}</h1>
				<input
					ref={c => (this.nameNode = c)}
					type="text"
					placeholder="输入名字"
				/>
				&nbsp;
				<input
					ref={c => (this.ageNode = c)}
					type="text"
					placeholder="输入年龄"
				/>
				&nbsp;
				<button onClick={this.addPerson}>添加</button>
				<ul>
					{this.props.persons.map(p => {
						return (
							<li key={p.id}>
								{p.name}--{p.age}
							</li>
						)
					})}
				</ul>
			</div>
		)
	}
} */
